/**
 * 问卷调查
 * @author kb
 * @date   2016/11/11
 */

let lf = liefeng,
    ajax = lf.utils.ajax,
    getUrlParam = lf.utils.getUrlParam;

const questionnaireId = getUrlParam('questionnaireId');

let Checkbox = React.createClass({
    getInitialState(){
        return ({
            idx: this.props.idx,
            check: this.props.check || false,
            value: '',
        })
    },
    componentWillMount(){

        let answer = this.props.answer,
            data = this.props.data;

        if (answer.subjectItemid) {
            let cb = {
                idx: this.props.idx,
                dt: this.props.data.id + (answer.result && ',' + answer.result)
            }
            this.props.onChange(cb, true)
            this.setState({
                check: true,
                value: answer.result || ''
            })
        } else {
            this.setState({
                check: false,
                value: ''
            })
        }
    },
    checkFn(){
        let check = !this.state.check,
            value = this.state.value;

        this.setState({
            check: check,
            value: check ? value : ''
        })

        this.cbFn(check);

    },
    inputFn(){

        let $more = React.findDOMNode(this.refs.more);

        this.setState({
            check: true,
            value: $more.value
        })

        this.cbFn(true);

    },
    cbFn(check){
        let cb = '';

        if (check) {
            cb = {
                idx: this.props.idx,
                dt: this.props.data.id + (this.state.value && ',' + this.state.value)
            }
        } else {
            cb = {
                idx: this.props.idx,
                dt: ''
            }
        }

        this.props.onChange(cb)
    },
    render(){
        let data = this.props.data;
        return (
            <div>
                <div className="title">
                    <input type="checkbox" ref="check" name={data.subjectId} onChange={this.checkFn}
                           checked={this.state.check}/>
                    <label>{data.itemName}</label>
                </div>
                {
                    data.inputStatus == 2 ?
                        <input className={"more-input transition " + (this.state.check ? 'show' : '')} ref="more"
                               type="text" placeholder="选填" onChange={this.inputFn} value={this.state.value}/>
                        :
                        ''
                }
            </div>
        )
    }
})

let Radio = React.createClass({
    getInitialState(){
        return ({
            check: this.props.check || false,
            value: '',
        })
    },
    checkFn(){
        let $check = React.findDOMNode(this.refs.check);
        this.state.check = $check.checked;
        this.cbFn();
    },
    inputFn(){

        let $check = React.findDOMNode(this.refs.check),
            $more = React.findDOMNode(this.refs.more);

        if ($more.value != '') {
            $check.checked = true;
            this.state.check = $check.checked;
        }

        this.state.value = $more.value;

        this.cbFn();

    },
    componentWillMount(){
        let answer = this.props.answer,
            data = this.props.data;

        if (answer.subjectItemid) {
            this.setState({
                check: true,
                value: answer.result || ''
            })
        } else {
            this.setState({
                check: false,
                value: ''
            })
        }
    },
    componentWillReceiveProps(nextProps){

        if (nextProps.checked != undefined && this.state.check != nextProps.checked) {
            let value = this.state.value
            if (nextProps.checked == false) {
                value = ''
            }
            this.setState({
                check: nextProps.checked,
                value: value
            });
        }
    },
    cbFn(){
        this.props.onChange(this);
    },
    render(){
        let data = this.props.data;
        return (
            <div>
                <div className="title">
                    <input type="radio" ref="check" name={data.subjectId} onChange={this.checkFn}
                           checked={this.state.check}/>
                    {data.itemDesc ? <label className="desc">{data.itemDesc}分 </label> : ''}
                    <label>{data.itemName}</label>
                </div>
                {
                    data.inputStatus == 2 ?
                        <input className={"more-input transition " + (this.state.check ? 'show' : '')} ref="more"
                               type="text" placeholder="选填" onChange={this.inputFn} value={this.state.value}/>
                        :
                        ''
                }
            </div>
        )
    }
})

let Textarea = React.createClass({
    getInitialState(){
        return ({
            value: ''
        })
    },
    componentWillMount(){
        let answer = this.props.answer,
            data = this.props.data;

        if (answer && answer.result) {
            this.setState({
                value: answer.result || ''
            })
        }
    },
    onChange(){
        let $input = React.findDOMNode(this.refs.input);

        this.setState({value: $input.value});

        this.props.onChange($input.value)

    },
    render(){
        let data = this.props.data;
        return (
            <div>
                <textarea ref="input" rows="10" cols="30" onChange={this.onChange} value={this.state.value}/>
            </div>
        )
    }
})

let Subject = React.createClass({
    getInitialState(){
        let data = this.props.data,
            radioData = [],
            mulData = [];

        if (data.questionType == '1' || data.questionType == '4') {
            let isSubmit = [];
            data.items.map(()=> {
                isSubmit.push(false);
            })
            radioData = isSubmit;
        }

        return ({
            rData: '',
            mulData: mulData,
            radioData: radioData,
            radioChange: false,
        })
    },
    onChange(cb, noSubmit){
        let data = this.props.data

        if (data.questionType == '1' || data.questionType == '4') {
            this.radioCb(cb)
        } else if (data.questionType == '2') {
            this.mulChoseCb(cb, noSubmit)
        } else if (data.questionType == '3') {
            this.gapFillCb(cb)
        }
    },
    mulChoseCb(cb, noSubmit = false){
        let data = this.state.mulData,
            selsection = [];

        data[cb.idx] = cb.dt;

        data.map(e => {
            if (e) selsection.push(e)
        })

        let cbData = {
            subjectId: this.props.data.subjectId,
            data: selsection.join(";")
        };

        if (!noSubmit) this.props.onChange(cbData)
        

    },
    radioCb(cb){
        let state = this.state,
            isSubmit = [];
        state.radioData.map(()=> {
            isSubmit.push(false);
        })
        let radioData = isSubmit;
        radioData[cb.props.idx] = true;

        this.setState({
            radioData: radioData,
            radioChange: true
        })

        let cbData = {
            subjectId: this.props.data.subjectId,
            data: cb.props.data.id + (cb.state.value && ',' + cb.state.value)
        }

        this.props.onChange(cbData);
    },
    gapFillCb(cb){
        let cbData = {
            subjectId: this.props.data.subjectId,
            value: cb
        }
        this.props.onChange(cbData);
    },
    render(){    //多选 //单选 //填空 //打分
        
        let data = this.props.data,
            subList = '',
            subType = '',
            me = this;

        if (data.questionType != '3' && data.questionType) {
            subList = data.items.map((dt, idx) => {
                let answer = {};

                this.props.answerList.map(e => {
                    // console.log(e.subjectItemid == dt.id)
                    if (e.subjectItemid == dt.id) answer = e
                })

                if (data.questionType == '1' || data.questionType == '4') {

                    data.questionType == '1' ? subType = '单选题' : subType = '打分题'

                    let checked = this.state.radioData[idx];

                    if (answer.subjectItemid && !this.state.radioChange) checked = true;

                    return <Radio data={dt} onChange={me.onChange} checked={checked} idx={idx} answer={answer}/>

                }
                else if (data.questionType == '2') {
                    subType = '多选题'
                    return <Checkbox data={dt} onChange={me.onChange} idx={idx} answer={answer}/>

                }
            })
        }
        else {
            let answer = {}

            if (this.props.answerList) answer = this.props.answerList[0]
            
            subType = '填空题'
            subList = <Textarea data={data} onChange={me.onChange} answer={answer}/>
        }

        return (
            <div className="subject">
                <div className="subject-title">
                    <h3>{data.catoryDesc}</h3>
                    <h4>{data.subjectDesc} -- ({subType})</h4>
                </div>
                <div className="topic">{subList}</div>
            </div>
        )
    }
})


let Main = React.createClass({
    getInitialState(){
        return ({
            page: 0,
            transition: false,
            answerList: [],
            dataList: [],
            hasSubmit: [],
            rData: '',
            isEnd: false,
            maxNum: 0,
            sublist: '',
        })
    },
    componentWillMount(){
        let me = this;
        let dt = [];
        ajax({
            type: 'post',
            data: {
                questionnaireId: questionnaireId,
            },
            success: function (data) {
                me.checkSubmit(data.dataList);
            }
        }, lf.finger.api.survey.getSubjectsAndItems);
        ajax({
            type: 'post',
            data: {
                questionnaireId: questionnaireId,
            },
            success: function (data) {
                console.log(data)
                sessionStorage.tips = data.data.peroration;
            }.bind(me)
        }, lf.finger.api.survey.getQuestionnaireInfo);
    },
    checkSubmit(dt){
        let me = this;
        ajax({
            type: 'get',
            data: {
                questionnaireId: questionnaireId,
                userId: this.props.user.userId
            },
            success: function (data) {
                if (data.code == '200') {
                    //未来这一部分可以移动去success
                    let answerList = data.dataList,
                        page = 0,
                        maxNum = 0,
                        isEnd = false,
                        subList = '';

                    subList = dt.map((e1, idx)=> {
                        if (e1.questionType) {
                            maxNum++;
                            let answer = [];

                            answerList.map(e2 => {
                                if (e2.id == e1.subjectId) answer = e2.questionnaireVoteVoList
                            })
                            return <Subject data={e1} answerList={answer} onChange={me.onChange} idx={idx}/>
                        }
                    })

                    if (dt.length == 1) isEnd = true;

                    if (answerList.length == maxNum) {
                        page = answerList.length - 1;
                        isEnd = true;
                    }
                    else if (answerList.length > 0) {
                        page = answerList.length
                    }
                    let isSubmit = [];
                    answerList.map(()=> {
                        isSubmit.push(true);
                    })
                    me.setState({
                        dataList: dt,
                        maxNum: maxNum,
                        isEnd: isEnd,
                        subList: subList,
                        answerList: answerList,
                        hasSubmit: isSubmit,
                        // hasSubmit: new Array(answerList.length).fill(true),//todo chrome 低版本不支持
                        page: page,
                    })
                }
            }
        }, lf.finger.api.survey.queryAnswer);
    },
    ready(){

    },
    prevFn(){
        if (this.state.page > 0) {
            this.setState({
                page: this.state.page - 1,
                isEnd: false,
                transition: true,
            })
        }
        
    },
    nextFn(){

        let me = this;

        let state = this.state;

        console.log(!state.rData)

        if (!state.rData && !state.hasSubmit[state.page]) {
            alert('请填写答案')
            return;
        }
        else if (!state.rData && state.hasSubmit[state.page]) {
            this.success();
        }
        else {
            this.submit(state.rData)
        }

    },
    onChange(cb){
        this.state.hasSubmit[this.state.page] = false;
        this.state.rData = cb || '';
        // console.log(this.state.rData)
    },
    submit(dt){
        let user = this.props.user,
            state = this.state,
            me = this;

        let data = {
            projectId: user.projectId,
            userId: user.userId,
            subjectId: dt.subjectId,
            subjectItemid: dt.data && dt.data || '',
            result: dt.value && dt.value || '',
        }

        console.log('提交')
        if (!data.result && !data.subjectItemid && !state.hasSubmit[state.page]) {
            alert('请填写答案')
            return;
        }

        ajax({//点击发送内容
            type: 'post',
            data: data,
            success: function (data) {
                if (data.code == '200') me.success();
                else debugAlert(data.desc);
            }
        }, lf.finger.api.survey.createVotes)

    },
    success(){

        let state = this.state,
            next = state.page + 1,
            toEnd = false;

        state.hasSubmit[state.page] = true;
        state.rData = '';

        if (next >= state.maxNum - 1) toEnd = true
        
        if (!state.isEnd) {
            this.setState({
                page: state.page + 1,
                isEnd: toEnd,
                transition: true,
            })
        } else {
            this.end();
        }
    },
    end(){

        let dt = {
            content: sessionStorage.tips
        }

        const yesCb = () => {
            ajax({
                type: 'post',
                data: {
                    questionnaireId: questionnaireId,
                    userId: this.props.user.userId
                },
                success: function (data) {
                    console.log(data)
                    if (data.code == '200') {
                        lf.appJs.toast('提交成功')
                        setTimeout(()=> {
                            lf.appJs.doClose();
                        }, 300)
                    } else {
                        debugAlert(data.desc)
                    }
                    // lf.appJs.toast('提交成功')
                    //   setTimeout(()=>{
                    //     lf.appJs.doClose();
                    // },300)
                }
            }, lf.finger.api.survey.commitQuestionnaire);
        }

        confirm(dt, yesCb)
    },
    render(){

        let page = this.state.page * 100;

        return (
            <div className="list-reply">
                <div className={"sub-bg " + (this.state.transition ? 'transition' : '')}
                     style={{'width': this.state.maxNum * 100 + 'vw','left': -page + 'vw'}}>
                    {this.state.subList}
                </div>
                <div className="bottom">
                    <p className="page">当前第{this.state.page + 1}题/共{this.state.maxNum}题</p>
                    <div className="btn">
                        <a className={"prev " + (this.state.page == 0 ? "bank" : '')} href="javascript:;"
                           onTouchEnd={this.prevFn}>上一题</a>
                        <a className="next" href="javascript:;"
                           onTouchEnd={this.nextFn}>{this.state.isEnd ? '提交' : '下一题'}</a>
                    </div>
                </div>
            </div>
        )
    }
})

lf.bridgeJs.getUser(function (user) {
    React.render(
        <Main user={user}/>,
        document.getElementById('root'), function () {
            $('#root').css('background', 'none');
        }
    )
})